import traceback
from crawlers.utils import fetch_json_data, parse_timestamp
from crawlers.constants import (
    THEPAPER_BASE_URL,
    REQUEST_HEADERS,
    THEPAPER_HOT_ARTICLES_URL,
)


def process_likes_or_comments(likes_or_comments:str):
    """处理点赞或评论数，将其转换为整数

    Parameters:
        likes_or_comments: 点赞或评论数

    Returns:
        处理后的整数值
    """
    if "" == likes_or_comments:
        return 0
    else:
        return int(likes_or_comments)

def get_articles_from_thepaper():
    """从澎湃新闻获取热榜文章列表

    Returns:
        文章列表，每个包含标题、链接、图片链接、点赞数、评论数、关键词、发布时间
    """
    try:
        json_data = fetch_json_data(THEPAPER_HOT_ARTICLES_URL, REQUEST_HEADERS)

        hot_articles = []
        hot_articles_json = json_data['hotNews']
        for index, item in enumerate(hot_articles_json, 1):
          hot_article_info = {}
          hot_article_info['order'] = index
          hot_article_info['title'] = item['name']
          hot_article_info['url'] = f"{THEPAPER_BASE_URL}/newsDetail_forward_{item['contId']}"
          hot_article_info['photo_url'] = item['pic']
          hot_article_info['likes'] = process_likes_or_comments(item['praiseTimes'])
          hot_article_info['comment_count'] = process_likes_or_comments(item['interactionNum'])
          hot_article_info['created_at'] = parse_timestamp(item['pubTimeLong'], 'ms')
          hot_article_info['keywords'] = []
          if item.get("tagList"):
            for keyword in item['tagList']:
              new_keyword = {}
              new_keyword['name'] = keyword['tag']
              new_keyword['url'] = f"{THEPAPER_BASE_URL}/tag/{keyword['tagId']}"
              hot_article_info['keywords'].append(new_keyword)
          hot_articles.append(hot_article_info)
        return hot_articles
    except Exception as e:
        print("澎湃新闻热榜数据获取失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise
